﻿CREATE PROCEDURE [dbo].[TempSpaces_UpdateIds]
	@RangeReviewId INT
AS

BEGIN TRAN

--ArticleIds
Update TempSpaces
Set ArticleId = a.Id
From TempSpaces t
Inner Join Articles a on t.ArticleCode = a.Code and t.UOM = ISNULL(a.UOM, t.UOM) and a.RangeReviewId = @RangeReviewId

IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RAISERROR('Error completando ArticleIds.', 16, 1)
		RETURN
	END

--StoreIds
Update TempSpaces
Set StoreId = s.Id
From TempSpaces t
Inner Join Stores s on t.StoreCode = s.Code and s.CountryId = (Select CountryId From RangeReviews Where Id = @RangeReviewId)

IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RAISERROR('Error completando StoreIds.', 16, 1)
		RETURN
	END

--Planograms
Update TempSpaces
Set PlanogramId = p.Id
From TempSpaces t
Inner Join Planograms p on t.Planogram = p.Name and t.StoreId = p.StoreId

IF @@ERROR <> 0
	BEGIN
		ROLLBACK TRAN
		RAISERROR('Error completando PlanogramsIds.', 16, 1)
		RETURN
	END
    
COMMIT TRAN